layui.use(['table','form','layer','element','jquery','upload','laydate'], function(){
    var layer = layui.layer,
        form = layui.form,
        element = layui.element,
        laydate = layui.laydate,
        $ = layui.jquery,
        table = layui.table,
        upload = layui.upload;


    //通用搜索
    form.on('submit(search)', function(data)
    {
        layui.table.reload('dataTable', {
            where: data.field
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
        });
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    // 通用提交
    form.on('submit(popup-save)', function (data)
    {
       var index =layer.msg('提交中，请稍候', {
            icon: 16,
            time: false,
            shade: 0.3
        });
        $(data.elem).attr('disabled', true);
        $.ajax({
            url: data.form.action,
            type: data.form.method,
            dataType: 'json',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: $(data.form).serialize(),
            success: function (result) {
                if (result.code === 0 && result.url != '') {
                    layer.msg(result.msg, {time: 1300}, function(){
                        layer.closeAll();
                        table.reload('dataTable');
                    });
                } else {
                    layer.msg(result.msg);
                    $(data.elem).attr('disabled', false);
                    layer.close(index);
                }
            },
            error: function (xhr, state, errorThrown) {
                layer.close(index);
                layer.msg(state + '：' + errorThrown);
                $(data.elem).attr('disabled', false);
            }
        });
        return false;
    });


    //通用异步 添加 修必弹出层
    $(document).on('click', '.ajax-popup', function(event) {
        event.preventDefault();
        var self = $(this);
        if (self.attr('disabled')) return false;
        var url = self.attr('href') || self.data('url')  ;
        if (!url) return;
        var title=self.text();


        var index = layer.msg('提交中，请稍候', {
            icon: 16,
            time: false,
            shade: 0.3
        });

        $.get(url,function (html) {
            if (typeof html === 'object') {
                layer.msg(html.msg);
                return false;
            }

            layer.open({
                type:1,
                maxmin:true,
                content:html,
                area:['80%','96%'],
                title:title,
                zIndex:999,
                success: function() {
                    layui.form.render();
                }
            });
            layer.close(index);
        }, 'html');
        return false;
    });

    //通用异步 删除接口
    $(document).on('click', '.ajax-del', function(event) {
        event.preventDefault();
        var self = $(this);
        var url = self.attr('href') || self.data('url');
        if (!url) return;
        var ids =[self.data('id')];

        var data={
            _method:'delete',
            ids:ids
        };

        layer.confirm('确认'+$(this).text()+'吗？', function(index){
            ajax_request(url,data,'post',function (result) {
                if (result.code==0){
                    self.parents("tr").remove();
                }
                layer.msg(result.msg)

            });

        });
        return false;
    });
    //批量 通用异步 删除接口
    $(document).on('click', '.ajax-batch-del', function(event) {
        event.preventDefault();
        var self = $(this);
        var url = self.attr('href') || self.data('url');
        if (!url) return;

        var ids = [];
        var hasCheck = layui.table.checkStatus('dataTable');
        var hasCheckData = hasCheck.data;
        console.log(hasCheck);
        console.log(hasCheckData);

        if (hasCheckData.length>0){
            $.each(hasCheckData,function (index,element) {
                ids.push(element.id)
            })
        }
        console.log(ids);
        if (ids.length>0){
            layer.confirm('确认'+$(this).text()+'吗？', function(){
                var data={
                    _method:'delete',
                    ids:ids,
                };
                ajax_request(url,data,'post',function (result) {
                    layer.msg(result.msg);
                    layui.table.reload("dataTable");
                });
            })
        }else {
            layer.msg('请选择删除项')
        }

        return false;
    });

    //AJAX通用错误配置
    $(document).ajaxError(function(event, xhr) {
        if (xhr.status == 422) {
            layer.msg(lea.msg(responseJSON.message.errors || '数据校验失败'));
        } else if (xhr.status == 404) {
            layer.msg('请求的内容不存在');
        } else {
            layer.msg('服务器异常，请稍后再试~');
        }
    });
    //通用图片查看
    $(document).on('click', '.view-img', function(event) {
        var imgUrl =$(this).attr("href");
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            scrollbar: false,
            skin: 'layui-layer-nobg', //没有背景色
            shadeClose: true,
            content: "<img style='max-width: 100%;max-height:100%;' src='" + imgUrl + "'>"
        });
        return false;
    });

    function ajax_request(url,data,type, success, error,dataType,async) {
        console.log(999);
        console.log(data);

        console.log(999888);
        console.log(data.elem);
        var current =data.elem;

        var index = layer.msg('提交中，请稍候', {
            icon: 16,
            time: false,
            shade: 0.3
        });

        var type = type || 'get';//请求类型
        var dataType = dataType || 'json';//接收数据类型
        var async = async || true;//异步请求


        var success = success || function (result) {
                console.log(111112)
            if (result.code === 0 && result.url != '') {
                    setTimeout(function () {
                        location.href = result.url;
                    }, 1000);
                } else {
                    $(current).attr('disabled', false);
                    console.log(11111)
                console.log(current)
                    $(current).removeAttr("disabled");
                    $(current).attr('disabled',"");
            }
                layer.close(index);
                layer.msg(result.msg);
            };

        var error = error || function (xhr, state, errorThrown) {
                layer.close(index);
                layer.msg(state + '：' + errorThrown);
                console.log(state + '：' + errorThrown);
                $(current).removeAttr("disabled");
                $(current).attr('disabled',"");
            };
        var data =data.field || data;
        $.ajax({
            'url': url,
            'data': data,
            'type': type,
            'dataType': dataType,
            'async': async,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success:success,
            error :error,
            'beforeSend': function () {
                loadingIndex = layer.msg('加载中', {
                    icon: 16,
                    shade: 0.01
                }, 300);
            },
            'complete': function (e) {
                layer.close(loadingIndex);
            }
        });
    }

    //侧边栏 定位
    var $SIDEBAR_MENU = $('.layui-side-scroll'),
        //CURRENT_URL = window.location.href.split('?')[0];
    CURRENT_URL = window.location.pathname.split('?')[0];
    console.log(window.location.href);
    console.log(CURRENT_URL);
    $SIDEBAR_MENU.find('a[href="' + CURRENT_URL + '"]').parents('li').addClass('layui-nav-itemed');
    $SIDEBAR_MENU.find('a[href="' + CURRENT_URL + '"]').parents('dd').addClass('layui-this');

   console.log( $SIDEBAR_MENU.find('a[href="' + CURRENT_URL + '"]').html());
    console.log(window.location.pathname);



});

function in_array(search,array){
    for(var i in array){
        if(array[i]==search){
            return true;
        }
    }
    return false;
}
/*变量处理*/
function isset() {
    var a = arguments,
        l = a.length,
        i = 0,
        undef;
    if (l === 0) {
        throw new Error("Empty isset")
    }
    while (i !== l) {
        if (a[i] === undef || a[i] === null) {
            return false
        }
        i++
    }
    return true
};

function empty(mixed_var) {
    var undef, key, i, len;
    var emptyValues = [undef, null, false, 0, "", "0"];
    for (i = 0, len = emptyValues.length; i < len; i++) {
        if (mixed_var === emptyValues[i]) {
            return true
        }
    }
    if (typeof mixed_var === "object") {
        for (key in mixed_var) {
            return false
        }
        return true
    }
    return false
};